var pickUpPiece = null;

// 点击棋子
$(".piece").click(function () {
    const name = $(this).attr('id')

    /////////// 执棋 ///////////
    if ($(this).data('color') === turnToMove) {
        // 当前棋子状态
        const status = $(this).data('status');

        // 放下所有棋子
        $(".piece").each(function () {
            pieceDown($(this));
            pickUpPiece = null;
        });

        // 取消所有可走位置
        $(".allowed-move").remove();

        // 如果status为down，则拿起棋子
        // 如果status为up，则放下棋子
        if (status == 'down') {
            pieceUp($(this));

            // 显示可走位置
            targetPositions = getMovePositions($(this));
            showMovePositions(targetPositions);
            pickUpPiece = $(this);
        }
    }
})

// 走棋
$('#chess-board').on('click', '.allowed-move', function () {
    var targetPiece = null;
    $(".piece").each(function () {
        if ($(this).data('status') === 'up') {
            targetPiece = $(this);
        }
    });
    const nX = $(this).data('x');
    const nY = $(this).data('y');

    const moveData = moveRecordPush(pickUpPiece, nX, nY)
    pieceMove(pickUpPiece, nX, nY)

    // 切换下棋方
    if (turnToMove === 'black') {
        turnToMove = 'red';
    } else {
        turnToMove = 'black';
    }

    // 新增消息记录
    if (moveData.role === "user") {
        newMessage(moveData.role, null, moveData.string)

        let record = {
            "role": moveData.role,
            "text": moveData.string,
            "board": boardToArray(),
            "id": moveData.piece,
            "f": moveData.from.string,
            "t": moveData.to.string
        }

        addMessageRecord(record)
    }

    // 请求AI
    if (turnToMove !== userHolderColor) {
        e = newMessage("ai", null, null)
        requestAI(e)
    }
})

// 选择颜色
$(".select-color").click(function () {
    if (userHolderColor !== null) {
        newMessage("system", "对局已开始");
        return;
    }
    const color = $(this).data('color');
    let colorString = "红"
    let colorString2 = "黑"
    let roleString = "我"
    if (color === 'black') {
        colorString = "黑"
        colorString2 = "红"
        roleString = "你"
    }
    initLayout(color);
    $('.piece').show();

    const text = "我执" + colorString + "棋，你执" + colorString2 + "棋，" + roleString + "先行。"
    newMessage("user", null, text);
    addMessageRecord({
        "role": "user",
        "text": text
    })
})

// 悔棋
$('.undo').click(function () {
    undoMoveRecord()
})

// 重新开始
$('.restart').click(function () {
    location.reload();
})




